<?php

namespace app\controllers;

use app\models\cacheModel\AdminRoleModel as AdminRoleCacheModel;
use app\models\CommonModel;
use app\models\tableModel\AdminRoleModel as AdminRoleDBModel;
use Behat\Gherkin\Exception\Exception;
use Yii;
use yii\base\UserException;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\HttpException;

class SiteController extends BaseController
{

    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {

        return [
            'access' => [
                'class' => AccessControl::className(),
                // 'only' => ['logout', 'index'],
                'rules' => [
                    [
                        'actions' => [
                            'error'
                        ],
                        'allow' => true,
                        'roles' => ['?']
                    ],
                    [
                        'actions' => [
                            'index',
                            'error'
                        ],
                        'allow' => true,
                        'roles' => ['@']
                    ]
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [

                ],
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function actions()
    {

        return [];
    }

    /**
     * 网站首页
     * @return string
     */
    public function actionIndex()
    {

        // ******************** 1、用户基本信息 ********************
        // 用户基本信息
        $userInfo = \Yii::$app->user->identity;
        // 默认头像
        if (empty($userInfo->avatar)) $userInfo->avatar = '/images/default-avatar.jpg';
        // 头像
        $userInfo->avatar = CommonModel::addImgHost($userInfo->avatar);
        // 判断账号中所属角色
        if (empty($userInfo['role_id'])) {
            return $this->showError(403, '您的账号角色未分配，请联系管理员。');
        }


        // ******************** 2、用户角色信息 ********************
        // 角色缓存模块
        $cacheRoleModel = AdminRoleCacheModel::loadModel($userInfo['role_id']);
        // 空的从数据库获取
        if (!$cacheRoleModel) {
            $cacheRoleModel = AdminRoleCacheModel::loadModelDB($userInfo['role_id']);
            $cacheRoleModel->saveData(); // 存储下
        }
        // 空的报错
        if (!$cacheRoleModel) {
            return $this->showError(403, '您的账号角色不存在，请联系管理员。');
        } else if ($cacheRoleModel['status'] != AdminRoleDBModel::getStatOpen()) {
            return $this->showError(403, '您的账号角色已被禁用，请联系管理员。');
        }

        // 需要更新下缓存|PS.更新失败了，暂时不做提示了。首页用户使用才是王道
        if ($cacheRoleModel->getAttribute('needSave')) {
            $cacheRoleModel->saveData();
        }

        return $this->render('index', [
            'userInfo' => $userInfo,
            'menu' => $cacheRoleModel['menu']
        ]);
    }

    /**
     * 错误页面
     * @return string|void
     */
    public function actionError()
    {

        $previousPage = Yii::$app->request->referrer;
        $exception = Yii::$app->getErrorHandler()->exception;

        if ($exception instanceof HttpException) {

            $code = $exception->getCode();
        } else {

            $code = $exception->getCode();
        }

        if ($exception instanceof Exception) {

            $name = $exception->getName();
        } else {

            $name = Yii::t('yii', 'Error');
        }

        if (!isset($code)) {

            $code = 500;
        }

        if ($exception instanceof UserException) {

            $message = $exception->getMessage();
        } else {

            $message = Yii::t('yii', 'An internal server error occurred.');
        }

        if (Yii::$app->getRequest()->getIsAjax()) {

            return $this->jsonFail($name, $code, [
                'errorDetail' => $message,
                'errorCode' => $code
            ]);
        } else {
            return $this->renderAjax('error', [
                'title' => $name,
                'message' => $message,
                'errorCode' => $code,
                'previousPage' => $previousPage
            ]);
        }
    }
}
